
from rest_framework.generics import GenericAPIView
from rest_framework import mixins, status, viewsets
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
# JWT
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

from .models import UserFav, UserLeavingMessage, UserAddress
from .serializers import UserFavSerializer, UserFavDetailSerializer, LeavingMessageSerializer, AddressSerializer
from utils.permissions import IsOwnerOrReadOnly

# Create your views here.


class UserFavAPIView(mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.ListModelMixin, GenericAPIView):
    # serializer_class = UserFavSerializer  # 已被动态设置所以无需配置
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly, )  # 限制权限，只有登录的用户才可以调用，IsOwnerOrReadOnly只能访问自己相关的数据
    authentication_classes = (JSONWebTokenAuthentication, )  # 配置验证使用 JWT 验证
    lookup_field = "goods_id"
    lookup_url_kwarg = "goods_id"

    def get(self, request, *args, **kwargs):
        goods_id = kwargs.get("goods_id", 0)
        if goods_id:
            print('------ 详情{0} ------'.format(goods_id))
            return self.retrieve(request, *args, **kwargs)
        else:
            print('------ 收藏列表 ------')
            return self.list(request, *args, **kwargs)

    def post(self, request):
        """
        用户添加/取消收藏
        :param request: 商品ID
        :return:
        """
        goods_id = request.data.get("goods")
        goods = self.get_queryset().filter(goods_id=goods_id)
        if goods.count() > 0:
            print('------ 取消收藏 ------')
            goods.delete()
            data = {
                "msg": "已取消收藏"
            }
            return Response(data=data, status=status.HTTP_204_NO_CONTENT)
        else:
            print('------ 新建收藏 ------')
            return self.create(request)

    def get_queryset(self):
        return UserFav.objects.filter(user=self.request.user)

    # 动态设置 serializer
    def get_serializer_class(self):
        if self.request is None:
            return UserFavSerializer
        if self.request.method == 'GET':
            goods_id = self.request.query_params.get("goods_id", 0)
            if goods_id:
                return UserFavDetailSerializer
            else:
                return UserFavSerializer
        else:
            return UserFavSerializer

    def perform_destroy(self, instance):
        instance.delete()


class LeavingMessageAPIView(mixins.ListModelMixin, GenericAPIView):
    """
    get:
    获取留言列表.
    post:
    新建图书.
    """
    serializer_class = LeavingMessageSerializer
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly,)  # 限制权限，只有登录的用户才可以调用，IsOwnerOrReadOnly只能访问自己相关的数据
    authentication_classes = (JSONWebTokenAuthentication,)  # 配置验证使用 JWT 验证

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def get_queryset(self):
        return UserLeavingMessage.objects.filter(user=self.request.user)


class UserAddressViewSet(viewsets.ModelViewSet):
    """
    收货地址管理
    list:
        获取收货地址
    create:
        添加收货地址
    update:
        更新收货地址
    delete:
        删除收货地址
    """
    serializer_class = AddressSerializer
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly,)  # 限制权限，只有登录的用户才可以调用，IsOwnerOrReadOnly只能访问自己相关的数据
    authentication_classes = (JSONWebTokenAuthentication,)  # 配置验证使用 JWT 验证

    def get_queryset(self):
        return UserAddress.objects.filter(user=self.request.user)
